package pl.wroc.pwr.docs.repos.webapp.web;

import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;

import pl.wroc.pwr.docs.repos.webapp.repo.Document;
import pl.wroc.pwr.docs.repos.webapp.repo.DocumentDao;

@WebServlet(urlPatterns="/document-display")
public class DocumentDisplayServlet extends HttpServlet{
	private static final long serialVersionUID = 1L;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		Integer id = Integer.parseInt(req.getParameter("id"));
		ServletContext context = getServletContext();
		DataSource ds = (DataSource) context.getAttribute("connectionPool");
		DocumentDao dao;
		Connection con = null;
		Document document = null;
		String content = null;
		String indexedContent = null;
		
		try {
			con = ds.getConnection();
			dao	= new DocumentDao(con);
			document = dao.getDocument(id);
			content = dao.getContent(document);
			indexedContent = dao.getIndexedContent(id);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if(con != null){
				try {
					con.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
		}
		
		req.setAttribute("document", document);
		req.setAttribute("content", content);
		req.setAttribute("indexedContent", indexedContent);
		
		getServletContext().getRequestDispatcher("/document.jsp").forward(req, resp);
	}
}